<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="70px">
        <el-form-item label="物料编码">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请输入物料编码"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input
            v-model="searchParam.materialName"
            placeholder="请输入物料名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="图号">
          <el-input
            v-model="searchParam.figureNumber"
            placeholder="请输入图号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="物料类型">
          <el-select
            v-model="searchParam.materialType"
            placeholder="请选择物料类型"
            clearable
          >
            <el-option
              v-for="item in dictionaryStore.filterDictList('MaterialType')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <!-- <el-button type="primary" @click="syncBtn()" :disabled="syncBtnLoading"
          >同步物料</el-button
        > -->
        <!-- v-if="authAllPerm(['npm:mdmmaterial:sync'])" -->
        <el-button type="primary" @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <!-- v-if="authAllPerm(['npm:mdmmaterial:add'])" -->
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="stopParam()"
          >批量停用</el-button
        >
        <!-- v-if="authAllPerm(['npm:mdmmaterial:stop'])" -->
        <el-button type="primary" @click="excelBoxOpen">导入 </el-button>
        <!-- v-if="authAllPerm(['npm:mdmmaterial:import'])" -->
        <el-button
          type="primary"
          class="ml-3"
          @click="
            useDownload('/wms/mdmmaterial/export', '物料主数据', searchParam)
          "
          v-if="authAllPerm(['npm:mdmmaterial:export'])"
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
        <el-dialog
          :close-on-click-modal="false"
          title="物料主数据数据导入"
          v-model="excelBox"
          width="555px"
        >
          <div>
            <el-button
              @click="
                useDownload(
                  '/wms/mdmmaterial/exportTemp',
                  '物料主数据上传模板',
                  searchParam
                )
              "
            >
              <template #icon>
                <i-ep-download />
              </template>
              物料主数据上传模板下载
            </el-button>
          </div>
          <div style="margin-top: 10px">
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              ref="onload_exl"
              @change="getfilepath"
            />
            <el-button
              @click="upload"
              :disabled="uploadBtn"
              style="cursor: pointer"
              >上传</el-button
            >
          </div>
        </el-dialog>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="table1"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        :header-cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="存货编码"
          prop="materialCode"
          min-width="120"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="物料名称"
          prop="materialName"
          min-width="150"
          show-overflow-tooltip
          align="left"
        >
          <template #default="scope">
            <span style="text-align: left"> {{ scope.row.materialName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="物料类型"
          prop="materialType"
          min-width="100"
          show-overflow-tooltip
          align="left"
        >
          <template #default="scope">
            {{ useDictionary("MaterialType", scope.row.materialType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="特殊维修"
          prop="ownAssets"
          min-width="100"
          show-overflow-tooltip
          align="left"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.ownAssets === 1">是</el-tag>
            <el-tag type="info" v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="报废追踪"
          prop="isBatchManage"
          min-width="100"
          show-overflow-tooltip
          align="left"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.isBatchManage === 1"
              >是</el-tag
            >
            <el-tag type="info" v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="短号"
          prop="shortCode"
          min-width="100"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="工厂"
          prop="plantCode"
          width="100"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="外来编号"
          prop="srcCode"
          min-width="100"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="图号"
          prop="figureNumber"
          min-width="140"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="国产件标识"
          prop="lcCkd"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.lcCkd === 1">是</el-tag>
            <el-tag type="info" v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="物料状态"
          prop="materialState"
          min-width="90"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("MaterialState", scope.row.materialState) }}
          </template>
        </el-table-column>
        <el-table-column
          label="物料规格"
          prop="materialSpecification"
          min-width="140"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="计量单位"
          prop="unitCode"
          min-width="90"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("MeasurementUnit", scope.row.unitCode) }}
          </template>
        </el-table-column>
        <el-table-column
          label="质检比例"
          prop="testProp"
          min-width="140"
          show-overflow-tooltip
          align="left"
        />
        <!-- <el-table-column
          label="启用状态"
          prop="enabled"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="修改时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="修改人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="260" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <!-- v-if="authAllPerm(['npm:mdmmaterial:check'])" -->
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <!-- v-if="authAllPerm(['npm:mdmmaterial:edit'])" -->
            <el-button
              type="primary"
              size="small"
              link
              @click="handleTableDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
            <!-- v-if="authAllPerm(['npm:mdmmaterial:delete'])" -->
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <npmmdmmaterial-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id: string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { authAllPerm } from "@/utils/index";

const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "NPMMDMMATERIAL",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/wms/mdmmaterial/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  materialCode: "",
  materialName: "",
  materialType: "",
  plantId: "",
  figureNumber: "",
};

const deleteParam = {
  api: "/wms/mdmmaterial/delete",
  data: {},
};
// 批量停用接口
const stopParam = async () => {
  ElMessageBox.confirm("确定批量停用吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await request({
        url: "/wms/mdmmaterial/disabled",
        method: "post",
        data: { ids: ids.value },
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "批量停用成功",
        });
      }
      getTableList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消停用",
      });
    });
};

// 数据请求错误后处理
function requestError() {}

const table1 = ref([]);
const mdmmatgroup: any = ref([]);

const dataCallBack = ref((res: any) => {
  for (let j = 0; j < res.length; j++) {
    for (let i = 0; i < mdmmatgroup.value.length; i++) {
      if (res[j].materialGroupId == mdmmatgroup.value[i].id) {
        res[j].materialGroupId = mdmmatgroup.value[i].materialGroupName;
      }
    }
  }
  table1.value = res;

  return table1.value;
}); // 无需二次数据处理&不传赞数也行

const resMdmmatgroup = async () => {
  await request({
    url: "npm/mdmmatgroup/getList",
    method: "post",
    data: {},
  }).then((res) => {
    mdmmatgroup.value = res.data;
  });
};

// const dataCallBack = ref(undefined);
// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(async () => {
  //await resMdmmatgroup();
  getTableList();
});

const addDialog: any = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/wms/mdmmaterial/get/${id}`,
    method: "get",
  }).then((data) => {
    addDialog.data = data.data;

    addDialog.visible = true;
  });
}

/** 打开物料主数据表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改物料主数据";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增物料主数据";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开物料主数据表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "物料主数据详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
  addDialog.rulesValue = false;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

// 导入excel
const uploadApi = "/wms/mdmmaterial/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });
      excelBox.value = false;
      uploadBtn.value = false;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}

let syncBtnLoading = false;
// 点击同步按钮
const syncBtn = () => {
  syncBtnLoading = true;
  ElMessageBox.confirm("确定同步吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await request({
        url: "/wms/mdmmaterial/synchronization",
        method: "post",
        data: {},
      });

      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "同步成功",
        });
        syncBtnLoading = false;
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消同步",
      });
      syncBtnLoading = false;
    });
};
</script>
<style lang="scss" scoped>
/* 去除选中时蓝色边框（下面两个都要加上） */

// :deep(.el-input .el-input__wrapper.is-focus) {
//   outline: none !important;
// }
// :deep(.el-select .el-input.is-focus .el-input__wrapper) {
//   outline: none !important;
// }

// :deep(.el-select .el-input .el-input__inner) {
//   border-color: #dcdfe6 !important;
//   outline: none;
// }
</style>
